
<template>
  <div class="card flex justify-content-center">
    <Dialog v-model:visible="visible" position="top" modal header="新增管理员" :style="{ width: '50vw' }">
      <form class="">
				<FormItem label="用户名" id="username">
					<InputText v-model="username" type="text" placeholder="请输入用户名" :class="{ 'p-invalid': usernameError }"  />
        	<small class="p-error">{{ usernameError || '&nbsp;' }}</small>
				</FormItem>
				<FormItem label="昵称" id="nickname">
					<InputText v-model="nickname" type="text" placeholder="请输入昵称" :class="{ 'p-invalid': nicknameError }"  />
        	<small class="p-error">{{ nicknameError || '&nbsp;' }}</small>
				</FormItem>
				<FormItem label="手机号" id="mobile">
					<InputText v-model="mobile" type="text" placeholder="请输入手机号" :class="{ 'p-invalid': mobileError }"  />
        	<small class="p-error">{{ mobileError || '&nbsp;' }}</small>
				</FormItem>
				<FormItem label="密码" id="password">
					<InputText v-model="password" type="text" placeholder="请输入密码" :class="{ 'p-invalid': passwordError }"  />
        	<small class="p-error">{{ passwordError || '&nbsp;' }}</small>
				</FormItem>
      </form>
      <template #footer>
        <Button label="关闭" icon="pi pi-times" @click="handleClose" text />
        <Button label="提交" type="submit" icon="pi pi-check" @click="onSubmit" autofocus />
      </template>
    </Dialog>
    <Toast />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Dialog, Button, InputText, Toast, useToast } from '@/utils/primevue'
import FormItem from '@/components/FormItem';
import { useField, useForm } from 'vee-validate';
import * as Yup from 'yup';
import { useAdminStore } from '@/stores/admin';
import type { TAdminReq } from '@/typing/admin';
const adminStore = useAdminStore()
const visible = ref(false);
const toast = useToast();

const emits = defineEmits(['reload'])

const openDialog = () => {
  visible.value = true;
}

// 定义验证规则
const validationSchema = Yup.object({
	username: Yup.string().required('请输入用户名').trim(),
	nickname: Yup.string().required('请输入昵称').trim(),
	mobile: Yup.string().required('请输入手机号').length(11).trim(),
	password: Yup.string().required('请输入密码').trim().min(6, '密码最少6位'),

});
const { handleSubmit, resetForm } = useForm({ validationSchema });
const { errorMessage: usernameError, value: username } = useField<string>('username');
const { errorMessage: nicknameError, value: nickname } = useField<string>('nickname');
const { errorMessage: mobileError, value: mobile } = useField<string>('mobile');
const { errorMessage: passwordError, value: password } = useField<string>('password');

const handleClose = () => {
  visible.value = false
}

const onSubmit = handleSubmit((values) => {
	adminStore.createAdmin(values as TAdminReq, (res: any)=> {
		visible.value = false
		emits('reload')
		toast.add({ severity: 'success', summary: res.msg, life: 3000 });
		resetForm()
	})
});

defineExpose({openDialog})

</script>
